import 'package:flutter/material.dart';
import 'package:talk/pages/device/x_device_router.dart';
import 'package:talk/src/utils/device_utils.dart';
import 'package:talk/tools/widgets/my_app_bar.dart';

import '../../commponets/ItemView.dart';
import '../../routers/fluro_navigator.dart';

/// design/4商品/index.html#artboard5
class QrCodePage extends StatefulWidget {
  const QrCodePage({
    super.key,
    this.isAdd = true,
    this.isScan = false,
    this.heroTag,
    this.goodsImageUrl,
  });

  final bool isAdd;
  final bool isScan;
  final String? heroTag;
  final String? goodsImageUrl;

  @override
  State<QrCodePage> createState() => _QrCodePageState();
}

class _QrCodePageState extends State<QrCodePage> {
  final TextEditingController _codeController = TextEditingController();

  String _scanData = "";

  @override
  void initState() {
    super.initState();
    WidgetsBinding.instance.addPostFrameCallback((_) {
      if (widget.isScan) {
        _scan();
      }
    });
  }


  Future<void> _scan() async {
    if (Device.isMobile) {
      NavigatorUtils.unfocus();
      // 延时保证键盘收起
      await Future.delayed(const Duration(milliseconds: 500));
      if (!mounted) return;

      // 使用pushNamedAndRemoveUntil并获取返回值
      final result = await Navigator.of(context).pushNamed('/qrcodeScanner');

      if (result != null && mounted) {
        setState(() {
          _scanData = result.toString();
          _codeController.text = _scanData;
        });
      }
    } else {
      print("当前平台暂不支持");
    }
  }


  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: MyAppBar(
        centerTitle: '添加设备',
        backgroundColor: Colors.transparent,
        dropdownWidth: 140,
        dropdownBackgroundColor: Colors.white,
        dropdownBorderRadius: 20,
        // elevation: 0,
        // leading: IconButton(
        //   icon: const Icon(Icons.arrow_back, color: Colors.white),
        //   onPressed: () => Navigator.of(context).pop(),
        // ),
      ),
      body: Stack(
        children: <Widget>[
          // 使用官方 TextField 组件替代 TextFieldItem
          Padding(
            padding: const EdgeInsets.symmetric(horizontal: 16.0, vertical: 30.0),
            child: TextField(
              controller: _codeController,
              decoration: const InputDecoration(
                labelText: '商品条码',
                hintText: '选填',
                border: OutlineInputBorder(),
                suffixIcon: Icon(Icons.qr_code_scanner, color: Colors.blue),
              ),
              onTap: _scan,
            ),
          ),

          // 显示扫码结果的区域
        ],
      ),






    );
  }
}

